package com.imau.servlet;

import com.imau.bean.User;
import com.imau.mapper.UserMapper;
import com.imau.util.SqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    private SqlSession session;
    private UserMapper userMapper;

    @Override
    public void init() throws ServletException {

        this.session = SqlSessionUtil.getSqlSession();
        this.userMapper  = session.getMapper(UserMapper.class);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");

        resp.setContentType("text/html;charset=utf-8");

        //接收前端用户名和密码
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String remember = req.getParameter("remember");

        //判断

        User user = userMapper.selectByUserNameAndPassowrd(username, password);

        if(user !=null)
        {
            resp.sendRedirect(req.getContextPath()+"/admin.html");
        }else {
            resp.sendRedirect(req.getContextPath()+"/login.html");
        }


    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doPost(req,resp);
    }
}
